package com.tianji.promotion.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.promotion.constants.PromotionConstants;
import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.domain.po.ExchangeCode;
import com.tianji.promotion.domain.query.CodeQuery;
import com.tianji.promotion.domain.vo.ExchangeCodeVO;
import com.tianji.promotion.mapper.ExchangeCodeMapper;
import com.tianji.promotion.service.IExchangeCodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.promotion.utils.CodeUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.tianji.promotion.constants.PromotionConstants.COUPON_CODE_SERIAL_KEY;
import static com.tianji.promotion.constants.PromotionConstants.COUPON_RANGE_KEY;

/**
 * <p>
 * 兑换码 服务实现类
 * </p>
 *
 * @author mxl
 * @since 2024-06-30
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {

    private final StringRedisTemplate redisTemplate;

    /**
     * 异步生成兑换码
     * @param coupon
     */
    @Override
    @Async("generateExchangeCodeExecutor")
    public void asyncGenerateExchangeCode(Coupon coupon) {
        log.debug("开始生成兑换码"+Thread.currentThread().getName());
        // 1. 生成自增id 借助redis incr
        // 1.1 获取优惠券总数量
        Integer totalNum = coupon.getTotalNum();
        // 1.1 获取自增id
        Long increment = redisTemplate.opsForValue().increment(COUPON_CODE_SERIAL_KEY, totalNum);
        if(increment == null){
            throw new BizIllegalException("兑换码生成失败");
        }
        // 2. 调用工具类生成兑换码
        int maxSerilaNum = increment.intValue();
        int begin = maxSerilaNum-totalNum+1;
        List<ExchangeCode> list = new ArrayList();
        for(int serialNum=begin; serialNum<=maxSerilaNum; ++serialNum){
            String code = CodeUtil.generateCode(increment, coupon.getId());// increment自增id， coupon.getId()用于计算新鲜值
            ExchangeCode exchangeCode = new ExchangeCode();
            exchangeCode.setId(serialNum);  // 兑换码id
            exchangeCode.setCode(code);
            exchangeCode.setExchangeTargetId(coupon.getId());
            exchangeCode.setExpiredTime(coupon.getIssueEndTime());
            list.add(exchangeCode);
        }
        // 3. 将兑换码保存db
        this.saveBatch(list);

        // 4. 写入Redis缓存， member couponId score 兑换码的最大序列号
        redisTemplate.opsForZSet().add(COUPON_RANGE_KEY, coupon.getId().toString(), maxSerilaNum);

    }

    @Override
    public PageDTO<ExchangeCodeVO> queryCodePage(CodeQuery query) {
        // 1. 校验参数
        if(query == null){
            throw new BadRequestException("参数不能为空");
        }

        // 2. 按条件查询兑换码
        Page<ExchangeCode> page = this.lambdaQuery()
                .eq(query.getCouponId() != null, ExchangeCode::getExchangeTargetId, query.getCouponId())
                .eq(query.getStatus() != null, ExchangeCode::getStatus, query.getStatus())
                .page(query.toMpPageDefaultSortByCreateTimeDesc());
        List<ExchangeCode> records = page.getRecords();
        if(CollUtils.isEmpty(records)){
            return PageDTO.empty(page);
        }
        List<ExchangeCodeVO> vos = records.stream()
                .map(record -> BeanUtils.copyBean(record, ExchangeCodeVO.class))
                .collect(Collectors.toList());

        return PageDTO.of(page, vos);
    }

    // 修改兑换码对应的bitmap的值
    @Override
    public boolean updateExchangeCodeMark(long serialId, boolean flag) {
        String key = PromotionConstants.COUPON_CODE_MAP_KEY;
        Boolean result = redisTemplate.opsForValue().setBit(key, serialId, flag);

        return result!=null && result;
    }

    @Override
    public Long exchangeTargetId(long serialNum) {
        // 1.查询score值比当前序列号大的第一个优惠券
        Set<String> results = redisTemplate.opsForZSet().rangeByScore(
                COUPON_RANGE_KEY, serialNum, serialNum + 50000, 0L, 1L);
        if (CollUtils.isEmpty(results)) {
            return null;
        }
        // 2.数据转换
        String next = results.iterator().next();
        return Long.parseLong(next);
    }
}
